package com.ncs.cns.business.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.ncs.cns.business.dao.impl.ResourceDAO;
import com.ncs.cns.business.to.Resource;

public class ResourceService {

	private ResourceDAO resourceDAO;

	public ResourceService(Context context) {
		this.resourceDAO = new ResourceDAO(context);
	}

	public Bitmap downLoadImg(String src) throws IOException {
		URL url = new URL(src);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setDoInput(true);
		con.connect();
		File path = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "CNSImg" + File.separator);
		InputStream is = con.getInputStream();
		Bitmap bm = BitmapFactory.decodeStream(is);
		return bm;
	}

	public Bitmap getImg(Bitmap downloadPhoto) throws IOException {
		File path = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + File.separator + "CNSImg" + File.separator);
		if (!path.exists())
			path.mkdir();
		File file = new File(path, "abc.jpg");
		try {
			BufferedOutputStream out = new BufferedOutputStream(
					new FileOutputStream(file));
			downloadPhoto.compress(Bitmap.CompressFormat.JPEG, 50, out);
			out.flush();
			out.close();
			String filePath = file.getPath();
			return BitmapFactory.decodeFile(filePath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Resource> findByEventId(Integer eventId) {
		return resourceDAO.findByEventId(eventId);
	}

	public void add(Resource re) {
		resourceDAO.insert(re);		
	}
	
	public void updateResourceUrl(String url,int id){
		Resource rec = resourceDAO.get(id);
		rec.setResourceLocation(url);
		resourceDAO.update(rec);
	}
}
